<?php

/**
 * @see SmartL_Zend_Controller_Action
 */
require_once 'SmartL/Zend/Controller/Action.php';
//require_once 'ZendX/JQuery/Controller/Action/Helper/AutoComplete.php';
require_once 'Db/Record/Book.php';
require_once 'Db/Record/BookRelation.php';
require_once 'Db/Record/Author.php';
require_once 'Doctrine/Query.php';

class BookController extends SmartL_Zend_Controller_Action 
{	
	/**
	 * Parameter: 'author'=>id of author.
	 */
	public function getBooksByAuthorAction()
	{
		$query = new Doctrine_Query();
		$query->from('Db_Record_Book')
			->where('authorId = ?', $this->_getParam('id'));			

		$this->_helper->json($query->fetchArray());		
	}
		
	/**
	 * Parameter: 'id'=>book id
	 */
	public function getRelatedAction()
	{
		$id = $this->_getParam('id');
		
		$query = new Doctrine_Query();
		$query->select('a1.name, a2.name, b1.description, b2.description, b1.name, b2.name, r.id')
			->from('Db_Record_BookRelation r')
			->leftJoin('r.Book1 b1')
			->leftJoin('b1.Author a1')
			->leftJoin('r.Book2 b2')
			->leftJoin('b2.Author a2')
			->where('r.bookid1 = ?', $id)
			->orWhere('r.bookid2 = ?', $id)
			->orderBy('r.count DESC');
		
		$result = array();
		foreach ( $query->execute() as $item ) {
			if ( $item->Book1->id != $id ) {
				$author = $item->Book1->Author;
				$result[] = array('name'=>$item->Book1->name, 'author'=>$author->name, 
					'description'=>$item->Book1->description);
			}
			else {
				$author = $item->Book2->Author;
				$result[] = array('name'=>$item->Book2->name, 'author'=>$author->name, 
					'description'=>$item->Book2->description);
			}
		}
		
		$this->_helper->json($result);
	}
}